<template>
  <div class="app-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center;margin-bottom: 20px;"
    >
      <div>
        显示参数类型:
        <el-select
          v-model="requestBody.type"
          placeholder="请选择"
          size="small"
          style="margin-right: 10px"
          @change="selectedShowChange"
        >
          <el-option value="templateType" label="话术类型"></el-option>
          <el-option value="answerType" label="跳转类型"></el-option>
          <el-option value="recorder" label="录音员"></el-option>
          <el-option value="variable" label="参数"></el-option>
          <el-option value="jzdj" label="降噪等级"></el-option>
          <el-option value="sbms" label="识别模式"></el-option>
          <el-option value="category" label="分类场景"></el-option>
          <el-option value="intentionJudgeCondition" label="意向判断规则"></el-option>
        </el-select>
        值名称:
        <el-input
          v-model="requestBody.value"
          placeholder=""
          size="small"
          style="margin-right: 10px;width: 200px;"
        />
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          size="small"
          @click="getParamData"
        >
          查询
        </el-button>
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          size="small"
          @click="handleAdd"
        >
          新增
        </el-button>
        <el-select
          v-if="requestBody.type == 'category' && requestBody.category == ''"
          v-model="requestBody.category"
          placeholder="查询分类下的应用场景"
          size="small"
          style="margin-left: 10px"
          @change="selectedShowChange"
        >
          <el-option
            v-for="item in data"
            :value="item.name"
            :label="item.name"
            :key="item.id"
          ></el-option>
        </el-select>
        <el-button
          v-if="requestBody.type == 'category' && requestBody.category != ''"
          size="small"
          @click="backCategory"
        >
          返回分类查询
        </el-button>
        <span
          style="margin-left: 10px"
          v-if="requestBody.type == 'category' && requestBody.category != ''"
        >
          {{ requestBody.category }}分类：
        </span>
      </div>
    </div>
    <el-table
      :data="data"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      ref="multipleTable"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column v-if="requestBody.type == 'recorder'" prop="aiId" label="录音员标号"></el-table-column>
      <el-table-column prop="name" :label="showLabel"></el-table-column>
      <el-table-column v-if="requestBody.type == 'recorder'" label="操作" align="center" width="400">
        <template #default="{row}">
          <div style="display: inline-block;">
            <el-upload
              class="upload-audio"
              action=""
              :http-request="uploadAudio"
              :on-success="(response, file) => uploadAudioSuccess(response, file, row)"
              :show-file-list="false"
              :accept="'.wav'"
            >
              <el-button type="primary">上传试听音频</el-button>
            </el-upload>
          </div>
          <div style="display: inline-block;">
            <el-button type="primary" style="margin-left: 6px; margin-bottom: 4px" @click="startPlayOrPause(row)">
              {{ row.buttonText }}
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <div style="display: flex;align-items: center;">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="selectedAll"
          @change="handleSelectAll"
        >
          当页全选
        </el-checkbox>
        <el-button
          style="margin-left: 10px"
          type="danger"
          @click="handleDelete"
        >
          删除
        </el-button>
      </div>
      <el-pagination
        style="flex-shrink: 0;"
        v-show="total > 0"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="requestBody.pageNum"
        :page-size="requestBody.pageSize"
        @pagination="getParamData"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
    <audio ref="audio" :src="audioUrl"></audio>

    <!-- 添加录音员对话框 -->
    <el-dialog
      title="添加录音员"
      v-model="dialogVisible"
      width="30%"
      @close="handleClose"
    >
      <el-form :model="addFromReq" ref="recorderForm" label-width="120px">
        <el-form-item label="录音员标号">
          <el-input v-model="addFromReq.aiId"></el-input>
        </el-form-item>
        <el-form-item label="录音员名称">
          <el-input v-model="addFromReq.value"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetDialog">取 消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
</style>

<script>
import { addType, deleteType, getParamData, updateRecorder } from "@/api/talkTemplateBase/param";
import waves from '@/directive/waves'
import axios from "axios";
import request from "@/utils/request";
import { ElMessage } from "element-plus";

export default {
  directives: { waves },
  data() {
    return {
      // 获取到的话术模板数据
      data: [],
      total: 0,
      // 请求数据的请求对象
      requestBody: {
        type: 'templateType',
        value: '',
        category: '',
        pageNum: 1,
        pageSize: 10,
      },
      showLabel: '值',
      audio: '',
      audioName: '',
      selectedRows: [],
      selectedAll: false,
      isIndeterminate: false,
      // audio相关设置
      audioUrl: '',
      audioSetting: {
        playingId: -1,
        playing: false,
        speed: 1,
      },
      // 添加录音员
      dialogVisible: false,
      addFromReq: {
        aiId: '',
        value: ''
      }
    }
  },
  created() {
    this.getParamData()
  },
  methods: {
    // 获取数据
    getParamData() {
      getParamData(this.requestBody).then(response => {
        this.audioSetting.playing = false
        this.$refs.audio.pause()
        this.data = response.data.content
        if (this.requestBody.type === 'recorder') {
          this.data.forEach(row => {
            row.buttonText = '试听'
          })
          this.showLabel = '录音员名称'
        } else {
          this.showLabel = '值'
        }
        this.total = response.data.totalElements
        console.log(response, '参数数据')
      })
    },
    handleSelectionChange(selection) {
      this.selectedRows = []
      for (let i = 0; i < selection.length; i++) {
        this.selectedRows.push(selection[i].id)
      }
      const isSelectedAll = this.selectedRows.length === this.data.length
      if (isSelectedAll) {
        this.selectedAll = isSelectedAll
        this.isIndeterminate = false
      } else {
        this.selectedAll = isSelectedAll
        if (this.selectedRows.length !== 0) {
          this.isIndeterminate = true
        } else {
          this.isIndeterminate = false
        }
      }
    },
    handleSelectAll(value) {
      this.selectedAll = value
      this.isIndeterminate = false
      if (value) {
        this.$refs.multipleTable.toggleAllSelection()
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    selectedShowChange() {
      this.getParamData()
    },
    handleDelete() {
      // console.log(this.selectedRows, '要删除的id')
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.requestBody.ids = this.selectedRows
          deleteType(this.requestBody).then(response => {
            this.$message.success('删除成功')
            this.getParamData()
          })
        })
        .catch(() => {
          this.$message.info('取消操作')
        })
    },
    handleAdd() {
      if (this.requestBody.type === 'recorder') {
        // 添加录音员特殊处理
        this.dialogVisible = true
        return
      }
      this.$prompt('请输入要添加的值', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(({ value }) => {
          this.requestBody.value = value
          addType(this.requestBody).then(response => {
            this.requestBody.value = ''
            this.$message({
              type: 'success',
              message: '添加成功',
            })
            this.getParamData()
          }).catch(reason => {
            this.requestBody.value = ""
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入',
          })
        })
    },
    handleAddSubmit() {
      this.requestBody.aiId = this.addFromReq.aiId
      this.requestBody.value = this.addFromReq.value
      addType(this.requestBody).then(response => {
        this.$message({
          type: 'success',
          message: '添加成功',
        })
        this.getParamData()
      })
      this.requestBody.aiId = ''
      this.requestBody.value = ''
      this.dialogVisible = false
      this.resetDialog()
    },
    resetDialog() {
      this.dialogVisible = false
      this.addFromReq.aiId = ''
      this.addFromReq.value = ''
    },
    backCategory() {
      this.requestBody.value = ''
      this.requestBody.category = ''
      this.getParamData()
    },
    // beforeUpload(audio, row) {
    //   // const isMt10M = audio.size / 1024 / 1024 > 10
    //   // if (isMt10M) {
    //   //   this.$message.warning('上传音频大小不能超过 10MB!')
    //   //   return
    //   // }
    //   // return true
    //   console.log('before-upload')
    //   console.log('row', row)
    //   return true
    // },
    uploadAudio(options){
      const formData = new FormData;
      formData.append('file',options.file);
      request.post('/audio/uploadAudio', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }).then(res => {
        options.onSuccess(res, options.file)
      }).catch(error => {
        this.$message.error("上传音频失败!");
      })
    },
    uploadAudioSuccess(response, file, row) {
      row.audioPath = response.data
      updateRecorder(row).then(response => {
        this.$message.success('上传音频成功')
      })
    },
    // 获取音频
    async getAudioByPath(audioPath) {
      try {
        const response = await axios({
          url: audioPath,
          method: "GET",
          responseType: "blob"
        });
        if (response.data.type === "application/json") {
          // console.log('获取音频失败!')
          this.$message.error("获取音频失败!");
          return -1;
        }
        const audioBlob = new Blob([response.data], { type: "audio/mpeg" });
        this.audioUrl = URL.createObjectURL(audioBlob);
      } catch (error) {
        // console.log('获取音频失败!')
        this.$message.error("获取音频失败!");
        return -1;
      }
    },
    startPlayOrPause(row) {
      if (this.audioSetting.playing && this.audioSetting.playingId !== row.id) {
        // 如果正在播放，找出找播放的列，暂停，切换为新的
        this.data.forEach(item => {
          if (item.id === this.audioSetting.playingId) {
            this.audioSetting.playing = false
            this.$refs.audio.pause()
            item.buttonText = '试听'
          }
        })
      }
      this.audioUrl = row.audioPath
      this.audioSetting.playing ? this.pausePlay(row) : this.startPlay(row)
    },
    // 开始播放
    startPlay(row) {
      Promise.all([this.getAudioByPath(this.audioUrl)]).then(res => {
        if (res == -1) {
          return
        } else {
          this.audioSetting.playing = true
          this.audioSetting.playingId = row.id
          row.buttonText = '暂停'
          this.$refs.audio.play()
        }
      })
    },
    // 暂停
    pausePlay(row) {
      this.audioSetting.playing = false
      row.buttonText = '试听'
      this.$refs.audio.pause()
    },
  },
}
</script>
